<?php

$statsArray = array();

?>
    	<div id="content">

            <h2><span>Raider Availability</span></h2>
            <div class="box">
                <div class="contents">
<?php 
					require './site/dkp/dkpfunctions.php';
					displayAvailabilityMatrix(); 
?>

                </div>
            </div>
            <br />
    	</div>
					
<?php
// ------------------------------------------------------------- 
function displayAvailabilityMatrix() {
	global $statsArray;

	$roles = getRolesArray(); //  From dkpfunctions.php
	$raiderDisplayArray = getRaiderDisplayArray(); //  From dkpfunctions.php
	$dataArray = getFormattedAvailabilityArray($raiderDisplayArray);
/*
echo '<br /><br />';
print_r($statsArray);
echo '<br /><br />';
*/
	$dataArray = sortArray($dataArray);
	$roleName = '';
	$rowShading = '';

	// The bit to display the blocks
	if (!isset($_GET['weeks'])) {
		foreach($roles as $role) {
			$rowNum = 0;
			echo '<img src="'.$role['image'].'" height="25px" width="25px">&nbsp;<b>'.$role['RoleName'].'</b>';
			echo '<table style="border-collapse:collapse;">';
			foreach($dataArray[$role['RoleID']] as $class) {
				foreach($class as $raider) {
					$rowShading = '';
					if ($odd = $rowNum%2)
						$rowShading = ' background-color: #e8e8e8;';
					echo '<tr style="">
						<td width="105px" align="right" style="Padding: 2px;'.$rowShading.'">'.$raider['name'].'&nbsp;&nbsp;</td><td style="Padding: 2px;'.$rowShading.'">';
						echo $raider['blocks'];
						echo '</td>
					</tr>';
					$rowNum++;
				}
			}
			echo '</table>';
		}
	}

	// The bit to display the stats
	foreach($roles as $role) {
		$rowNum = 0;
		echo '<img src="'.$role['image'].'" height="25px" width="25px">&nbsp;<b>'.$role['RoleName'].'</b>';
		echo '<table style="border-collapse:collapse;">';
		foreach($dataArray[$role['RoleID']] as$class) {
			foreach($class as $key => $raider) {
				$rowShading = '';
				if ($odd = $rowNum%2)
					$rowShading = ' background-color: #e8e8e8;';
				echo '<tr style="">
					<td width="105px" align="right" style="Padding: 2px;'.$rowShading.'">'
						.$raider['name'].'&nbsp;&nbsp;</td>
					<td style="Padding: 2px;'.$rowShading.'">';
							//print_r($raider);
							$statAttended = ($statsArray[$raider['id']][attended])?$statsArray[$raider['id']][attended]:0;

							$statPastAvailable = ($statsArray[$raider['id']][pastAvailable])?$statsArray[$raider['id']][pastAvailable]:0;
							$statPastTBC = ($statsArray[$raider['id']][pastTBC])?$statsArray[$raider['id']][pastTBC]:0;
							$statPastUnavailable = ($statsArray[$raider['id']][pastUnavailable])?$statsArray[$raider['id']][pastUnavailable]:0;
							$statPastUnsigned = ($statsArray[$raider['id']][pastUnsigned])?$statsArray[$raider['id']][pastUnsigned]:0;
							$statPastTotal = $statPastAvailable + $statPastTBC + $statPastUnavailable + $statPastUnsigned;
							$statPastConversion = 0;
							if ($statPastAvailable != 0)
								$statPastConversion = round((100/$statPastAvailable)*$statAttended);

							$statFutureAvailable = ($statsArray[$raider['id']][futureAvailable])?$statsArray[$raider['id']][futureAvailable]:0;
							$statFutureTBC = ($statsArray[$raider['id']][futureTBC])?$statsArray[$raider['id']][futureTBC]:0;
							$statFutureUnavailable = ($statsArray[$raider['id']][futureUnavailable])?$statsArray[$raider['id']][futureUnavailable]:0;
							$statFutureUnsigned = ($statsArray[$raider['id']][futureUnsigned])?$statsArray[$raider['id']][futureUnsigned]:0;

							$z = 0;
							if ($statPastTotal != 0)
								$z = 100 / $statPastTotal;
							$a = round($z * $statAttended);
							$b = 100 - $a;
							$c = round($z * $statPastAvailable);
							$d = round($z * $statPastTBC);
							$e = round($z * $statPastUnavailable);
							$f = round($z * $statPastUnsigned);
							$g = 0;
							if ($statPastAvailable != 0)
								$g = round((100/$statPastAvailable)*$statAttended);
							$h = 100 - $g;
							$i = $c + ($c - $g);
							$chartAvailability = "http://chart.apis.google.com/chart?chs=375x175&cht=pc&chd=t:".$g.",".$h."|".$a.",".$b."|".$c.",".$d.",".$e.",".$f."&chco=00CC00,CC0000,00CC00,CC0000,00CC00,CCCC00,CC0000,444444&chl=Conversion: ".$g."%||Attended: ".$a."%|Absent: ".$b."%|Available: ".$c."%|Possible: ".$d."%|Unavailable: ".$e."%|Unsigned: ".$f."%&chtt=".$key.",+".date('D j M y')."&chf=bg,s,f1f1f1|c,s,f1f1f1";
							$tooltipAvailability = "<a href=\"".$chartAvailability."\" onmouseover=\"Tip('<img src=\'".$chartAvailability."\' width=\'375\' height=\'175\'>')\" onmouseout=\"UnTip()\"<img src=\"http://dmz-gaming.com/images/common/icons/chart_pie.png\" height=\"12px\"/></a>";

							$iconConversion = 'http://dmz-gaming.com/images/common/icons/accept.png';
							if ($statPastConversion < ($c - 25)) {
								$iconConversion = 'http://dmz-gaming.com/images/common/icons/arrow_down_red.png';
							} elseif ($statPastConversion < ($c - 10)) {
								$iconConversion = 'http://dmz-gaming.com/images/common/icons/arrow_down_blue.png';
							} elseif ($statPastConversion > ($c + 25)) {
								$iconConversion = 'http://dmz-gaming.com/images/common/icons/arrow_up_red.png';
							} elseif ($statPastConversion > ($c + 10)) {
								$iconConversion = 'http://dmz-gaming.com/images/common/icons/arrow_up_blue.png';
							}
							$iconConversion = '<img src="'.$iconConversion.'" height="12" />';

							echo $tooltipAvailability.' ('.$statAttended.','.$statPastAvailable.','.$statPastTBC.','.$statPastUnavailable.','.$statPastUnsigned.') '.$statPastAvailable.'/'.$statPastTotal.' - '.$c.'% - '.$a.'%a - '.$g.'%c '.$iconConversion.' - '.$i;
					echo '</td>
				</tr>';
				$rowNum++;
			}
		}
		echo '</table>';
	}

	echo '<br />(Attended, Available, TBC, Unavailable, Unsigned)';
	echo '<br />   Available / Raids - %available - %attended - %available converted to attended';
/*	
	<a href="index.htm" onmouseover="Tip('Some text')" onmouseout="UnTip()">Homepage </a>

echo '<br /><br />';
print_r($dataArray);
echo '<br /><br />';
*/
	//print_r(getAttendanceArray());
}
// ------------------------------------------------------------- 
function getFormattedAvailabilityArray($raiderDisplayArray) {
	$raidDates = getRaidDates();
	$attendanceArray = getAttendanceArray();
	$availabilityArray = getAvailabilityArray();
/*
echo '<br /><br />';
print_r($attendanceArray);
echo '<br /><br />';
*/
	$numRaids = count($raidDates);
	$blockPath = './site/dkp/images/availability/';
	$nameFormat = array("lineEnd" => "", "titleText" => "", "fontWeight" => "bold", "roleImage" => false, "classImage" => false);

	$formattedAvailabilityArray = array();

	foreach($availabilityArray as $raider) {
		$previousWeekNo = 0;
		$isPast = true;
		$id = $raider['MemberID'];
		$data = $raiderDisplayArray;
		$raiderDisplayName = getRaiderDisplayName($id, $data, $nameFormat);

		//  Cycle through the raids on this row
		$blocks = '';
		for($i=0;$i<$numRaids;$i++) {
			//Adds a gap between raid weeks
			$dayOfWeek = date('w',strtotime($raidDates[$i]));
			$weekNo = date('W',strtotime($raidDates[$i]));
			if ($weekNo == 1 && $previousWeekNo == 52)
				$previousWeekNo = 0;
			if ((($weekNo - $previousWeekNo) > 1) || ((($weekNo - $previousWeekNo) == 1) && ($dayOfWeek > 2)))
				$blocks .= '&nbsp;';
			$previousWeekNo = $weekNo;
			
			//  Is the current raid the first one in the future?  if yes, add a bigger gap.  Unhappy with just a gap to delineate
			if ((strtotime($raidDates[$i]) + (60*60*23)) > time() && $isPast) {
				$blocks .= '<img src="http://dmz-gaming.com/images/common/icons/arrow_right.png" title="Upcoming raids">';
				$isPast = false;
			}
			
			$attendance = 'Absent';
			if ($attendanceArray[$id][$raidDates[$i]]['Present'] == 1) {
				$attendance = 'Present';
				addStats($id,'attended',1);
			}
			
			$note = '';
			if ($raider[$raidDates[$i]]['note'])
				$note = ' - '.$raider[$raidDates[$i]]['note'];
				
				
			
			//  Add appropriate block for the signup type
			switch ($raider[$raidDates[$i]][type]) {
				case 1: 
				case 2: 
				case 3: 
					$block = '<img src="'.$blockPath.'available'.$attendance.'.gif" title="Available - '.$attendance.' - '.formatAvailabilityDate($raidDates[$i]).$note.'">'; 
					$stat = ($isPast)?'pastAvailable':'futureAvailable';
					addStats($id,$stat,1);
					break;
				case 4: 
					$block = '<img src="'.$blockPath.'possible'.$attendance.'.gif" title="To be confirmed - '.$attendance.' - '.formatAvailabilityDate($raidDates[$i]).$note.'">'; 
					$stat = ($isPast)?'pastTBC':'futureTBC';
					addStats($id,$stat,1);
					break;
				case 5: 
					$block = '<img src="'.$blockPath.'unavailable'.$attendance.'.gif" title="Unavailable - '.$attendance.' - '.formatAvailabilityDate($raidDates[$i]).$note.'">'; 
					$stat = ($isPast)?'pastUnavailable':'futureUnavailable';
					addStats($id,$stat,1);
					break;
				case 6: 
					$block = '<img src="'.$blockPath.'noshow'.$attendance.'.gif" title="No show - '.$attendance.' - '.formatAvailabilityDate($raidDates[$i]).$note.'">'; 
					$stat = ($isPast)?'pastUnavailable':'futureUnavailable';
					addStats($id,$stat,1);
					break;
				default : 
					$block = '<img src="'.$blockPath.'unsigned'.$attendance.'.gif" title="Unsigned - '.$attendance.' - '.formatAvailabilityDate($raidDates[$i]).'">'; 
					$stat = ($isPast)?'pastUnsigned':'futureUnsigned';
					addStats($id,$stat,1);
			}
			
			$blocks .= $block;
		}
		$formattedAvailabilityArray[$data[$id]['roleID']][$data[$id]['className']][$data[$id]['userName']]['id'] = $id;
		$formattedAvailabilityArray[$data[$id]['roleID']][$data[$id]['className']][$data[$id]['userName']]['name'] = $raiderDisplayName;
		$formattedAvailabilityArray[$data[$id]['roleID']][$data[$id]['className']][$data[$id]['userName']]['blocks'] = $blocks;
	}
	return $formattedAvailabilityArray;
}
// -------------------------------------------------------------
function addStats($id,$stat,$value,$modifier="Add") {
	global $statsArray;
	
	$statsArray[$id][$stat] = $statsArray[$id][$stat] + $value;
}
// -------------------------------------------------------------
function formatAvailabilityDate($date) {
// returns a date of af almost any format as: Ddd dd Mmm, for example Sat 30 Jun
	return date('D j M',strtotime($date));
}
// -------------------------------------------------------------
function getRaidDates() {
// Extracts the dates of all raids in RaidNinja within the last 6 weeks and those available for future signup
// Returns an array of these dates

	$endWeek = 0;
	$startWeek = 6;
	if (isset($_GET['weeks'])) {
		if (isset($_GET['start'])) {
			$from = $_GET['start'];
			$to = $_GET['weeks'];
			$endWeek = $from - $to;
			$startWeek = $from;		
		} else {
			$startWeek = $_GET['weeks'];		
		}
	}

    global $db;
    $result = $db->query('
		SELECT 
			DATE(r.raid_start) AS date
		FROM 
			dmzraid_raids r
		WHERE
			(r.raid_start < DATE_SUB(NOW(),INTERVAL '.$endWeek.' WEEK)
			AND	r.raid_start > DATE_SUB(NOW(),INTERVAL '.$startWeek.' WEEK))
			OR
			(r.display_start < NOW()
			AND	r.raid_start > NOW())
	') or error('Unable to fetch raid dates', __FILE__, __LINE__, $db->error());
	$raidDates = array();
	while ($cur_entry = $db->fetch_assoc($result)) {
		$raidDates[] = $cur_entry['date'];
	}

/*	$raidDates = array();
	
	//Past 30 raids
    $result = $db->query('
		SELECT 
			DATE(r.raid_start) AS date
		FROM 
			dmzraid_raids r
		WHERE 	r.raid_start < NOW()
		ORDER BY date DESC
		LIMIT 24
	') or error('Unable to fetch raid dates', __FILE__, __LINE__, $db->error());
	while ($cur_entry = $db->fetch_assoc($result)) {
		$raidDates[] = $cur_entry['date'];
	}
	$raidDates = array_reverse($raidDates);

	// Future raids
    $result = $db->query('
		SELECT 
			DATE(r.raid_start) AS date
		FROM 
			dmzraid_raids r
		WHERE 	r.display_start < NOW()
		AND		r.raid_start > NOW()
	') or error('Unable to fetch raid dates', __FILE__, __LINE__, $db->error());
	while ($cur_entry = $db->fetch_assoc($result)) {
		$raidDates[] = $cur_entry['date'];
	}

	print_r($raidDates);*/
	return $raidDates;
}
// -------------------------------------------------------------
function getAvailabilityArray() {
// Extracts signup status' for all active raiders over the last six weeks and upcoming raids
// Returns an array of arrays each containing the member info and all the signups

	$endWeek = 0;
	$startWeek = 6;
	if (isset($_GET['weeks'])) {
		if (isset($_GET['start'])) {
			$from = $_GET['start'];
			$to = $_GET['weeks'];
			$endWeek = $from - $to;
			$startWeek = $from;		
		} else {
			$startWeek = $_GET['weeks'];		
		}
	}

    global $db;
    $result = $db->query('
    	SELECT 
			cr.character_id,
			cr.raid_id,
			cr.signup_type,
			cr.signup_time as notice,
			cr.updated as notice2,
			cr.note as note,
			DATE(ra.raid_start) AS date,
			c.user_id,
			m.MemberID,
			m.Name,
			m.ForumID
		FROM
			dmzraid_character_raid cr,
			dmzraid_raids ra,
			dmzraid_characters c,
			dmzdkp_members m
		WHERE
			cr.raid_id IN (
				SELECT 
					r.raid_id
				FROM 
					dmzraid_raids r
				WHERE
					(r.raid_start < DATE_SUB(NOW(),INTERVAL '.$endWeek.' WEEK)
					AND	r.raid_start > DATE_SUB(NOW(),INTERVAL '.$startWeek.' WEEK))
					OR
					(r.display_start < NOW()
					AND	r.raid_start > NOW())
			)
			AND ra.raid_id = cr.raid_id
			AND ra.has_signups = "Y"
			AND c.character_id = cr.character_id
			AND m.RaidNinjaID = c.user_id
			AND m.Enabled = 1
		ORDER BY c.user_id, cr.character_id, cr.raid_id	
	') or error('Unable to fetch signup details', __FILE__, __LINE__, $db->error());

	$currMember = '';
	$availabilityArray = array();
	while ($cur_entry = $db->fetch_assoc($result)){
		if ($cur_entry['MemberID'] != $currMember) {
			$currMember = $cur_entry['MemberID'];
			$availabilityArray[$currMember]['MemberID'] = $cur_entry['MemberID'];
			$availabilityArray[$currMember]['character_id'] = $cur_entry['character_id'];
			$availabilityArray[$currMember]['raid_id'] = $cur_entry['raid_id'];
			$availabilityArray[$currMember]['user_id'] = $cur_entry['user_id'];
			$availabilityArray[$currMember]['Name'] = $cur_entry['Name'];
			$availabilityArray[$currMember]['ForumID'] = $cur_entry['ForumID'];
		}
		$availabilityArray[$currMember][$cur_entry['date']]['type'] = $cur_entry['signup_type'];
		$availabilityArray[$currMember][$cur_entry['date']]['notice'] = $cur_entry['notice'];
		$availabilityArray[$currMember][$cur_entry['date']]['notice2'] = $cur_entry['notice2'];
		$availabilityArray[$currMember][$cur_entry['date']]['note'] = $cur_entry['note'];
	}
	return $availabilityArray;
}
// ------------------------------------------------------------- 
function getAttendanceArray() {

	$endWeek = 0;
	$startWeek = 6;
	if (isset($_GET['weeks'])) {
		if (isset($_GET['start'])) {
			$from = $_GET['start'];
			$to = $_GET['weeks'];
			$endWeek = $from - $to;
			$startWeek = $from;		
		} else {
			$startWeek = $_GET['weeks'];		
		}
	}

    global $db;
    $result = $db->query('
		SELECT 
			rm.MemberID,
			DATE(dr.Date) AS RaidDate
		FROM
			dmzdkp_raidmembers rm,
			dmzdkp_raids dr
		WHERE
			dr.RaidID = rm.RaidID
			AND dr.Date < DATE_SUB(NOW(),INTERVAL '.$endWeek.' WEEK)
			AND	dr.Date > DATE_SUB(NOW(),INTERVAL '.$startWeek.' WEEK)
			AND dr.hidden = 0
	') or error('Unable to fetch signup details', __FILE__, __LINE__, $db->error());

	$attendanceArray = array();
	while ($cur_entry = $db->fetch_assoc($result)){
		$attendanceArray[$cur_entry['MemberID']][$cur_entry['RaidDate']]['Present'] = 1;
	}
	return $attendanceArray;
}
?>
